package controller;

import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JToggleButton;
import model.Player;
import model.Sequence;

public class TrackModifiedListener implements ItemListener {

	private Sequence sequence;
	private Player player;

	public TrackModifiedListener(Player player, Sequence sequence) {
		this.sequence = sequence;
		this.player = player;
	}

	@Override
	public void itemStateChanged(ItemEvent e) {
		String command = ((JToggleButton)e.getSource()).getActionCommand();
		int[] changeLocation = parseCommand(command); //Parse the command

		if(e.getStateChange() == ItemEvent.SELECTED) {
			if(!player.isPlaying()) {
				player.playNote(sequence,changeLocation[1]+1);
			}
			sequence.setNote(changeLocation[0], changeLocation[1]+1);
		} else {
			sequence.removeNote(changeLocation[0]);
		}
	}

	/**
	 * A Command should be in the format {COLUMN_NUMBER}_{ROW_NUMBER} to parse
	 * correctly.
	 * <br>e.g. 1_4 means at column 1 where is a note at 4.
	 * @param command The command to parse
	 * @return Location of the note where 0 is the column and 1 is the value.
	 */
	private int[] parseCommand(String command) {
		String[] strs = command.split("_");
		int[] arr = new int[strs.length];
		for(int i = 0; i < strs.length; i++) {
			arr[i] = Integer.parseInt(strs[i]);
		}
		return arr;
	}


}
